package org.bluweb.g4wicket.youtube;

import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.repeater.RepeatingView;
import org.bluweb.g4wicket.G4WicketPanel;

@SuppressWarnings("serial")
public class YouTubePanel extends G4WicketPanel {

	public enum AllowScriptAccess { always, never, sameDomain };
	
	private String movieId;
	private RepeatingView params;
	private WebMarkupContainer embed;
	private WebMarkupContainer object;
	
	private boolean autoPlay;
	
	public YouTubePanel( String id, String movieId ) {
		super( id );
		this.movieId = movieId;
		
		object = new WebMarkupContainer( "object" );
		add( object );
		
		params = new RepeatingView( "param" );
		object.add( params );

		embed = new WebMarkupContainer( "embed" );
		embed.add( new SimpleAttributeModifier( "type", "application/x-shockwave-flash" ) );
		object.add( embed );
		
		this.setClass( id );
	}

	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		
		StringBuilder movieUrl = new StringBuilder( "http://www.youtube.com/v/" );
		movieUrl.append( this.movieId );
		movieUrl.append( "?version=3&ap=%2526fmt%3D18&rel=0&color1=0xb1b1b1&color2=0xcfcfcf&feature=player_embedded&hd=1" ); 
		
		if( autoPlay ) {
			movieUrl.append( "&autoplay=1" );
		}
		
		WebMarkupContainer param = new WebMarkupContainer( params.newChildId() );
		param.add( new SimpleAttributeModifier( "name", "movie" ) );
		param.add( new SimpleAttributeModifier( "value", movieUrl ) );
		params.add( param );
		embed.add( new SimpleAttributeModifier( "src", movieUrl ) );
	}

	public void setAutoPlay(boolean autoPlay) {
		this.autoPlay = autoPlay;
	}

	public YouTubePanel setAllowScriptAccess( AllowScriptAccess value ) {
		return this.addSetting( "allowScriptAccess", value.toString() );
	}
	
	public YouTubePanel setAllowFullScreen( boolean allow ) {
		return this.addSetting( "allowFullScreen", String.valueOf( allow ) );
	}
	
	public YouTubePanel setClass( String className ) {
		SimpleAttributeModifier classModifier = new SimpleAttributeModifier( "class", className );
		embed.add( classModifier );
		object.add( classModifier );
		return this;
	}
	
	private YouTubePanel addSetting( String name, String value ) {

		WebMarkupContainer param = new WebMarkupContainer( params.newChildId() );		
		param.add( new SimpleAttributeModifier( "name", name ) );
		param.add( new SimpleAttributeModifier( "value", value ) );
		params.add( param );
		embed.add( new SimpleAttributeModifier( name, value ) );
		
		return this;
	}	
}
